package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        //使用pagehelper插件实现分页查询
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());

        //执行查询，返回对象必须使用Page对象，这是pagehelper插件提供
        Page page = categoryMapper.pageQuery(categoryPageQueryDTO);
        //获取到条数total和数据records
        long total = page.getTotal();
        List<Category> records = page.getResult();
        //将查询的结果封装到pageResult对象中返回给controller层
        return  new PageResult(total,records);
    }

    @Override
    public void updata(CategoryDTO categoryDTO) {

        Category build = Category.builder()
                .id(categoryDTO.getId())
                .name(categoryDTO.getName())
                .type(categoryDTO.getType())
                .sort(categoryDTO.getSort())
                .build();

        System.out.println(build);
        categoryMapper.updata(build);
    }

    @Override
    //根据id修改分类状态
    public void updataStatus(Integer status, Long id) {

        Category build = Category.builder()
                .id(id)
                .status(status)
                .build();
        categoryMapper.updata(build);
    }

    @Override
    public void save(CategoryDTO categoryDTO) {

        /*使用对象拷贝
        Category build = Category.builder()
               .name(categoryDTO.getName())
               .type(categoryDTO.getType())
               .sort(categoryDTO.getSort())
               .build();*/
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        //设置分类状态
        category.setStatus(StatusConstant.DISABLE);
        /** aop自动填充，
        //设置创建时间和修改时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        //设置创建人和修改人
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        */
        categoryMapper.save(category);


    }

    @Override
    public void delete(Long id) {
        categoryMapper.delete(id);
    }

    @Override
    public List<Category> list(Integer type) {
        List<Category> list1 = categoryMapper.list(type);

        return list1;

    }


}
